<template>
    <el-table 
      :data="processedTableData" 
      style="width: 100%" 
      border 
      :span-method="handleSpanMethod"
      v-loading="loading"
    >
      <!-- 主表信息列 -->
      <el-table-column prop="purret_code" label="退货单号" width="180" />
      <el-table-column prop="po_code" label="采购单号" width="180" />
      <el-table-column prop="po_name" label="采购单名称" width="150" />
      <el-table-column prop="vendor_name" label="供应商" width="150" />
      <el-table-column prop="vendor_code" label="供应商编码" width="150" />
      
      <!-- 商品详情列 -->
      <el-table-column prop="pro_name" label="商品名称" width="150" />
      <el-table-column prop="pro_code" label="商品编码" width="150" />
      <el-table-column prop="pro_brand" label="品牌" width="120" />
      <el-table-column prop="pro_model" label="型号" width="120" />
      <el-table-column prop="po_number" label="采购数量" width="100" align="right" />
      <el-table-column prop="podet_inbound_quantity" label="已入库数量" width="100" align="right" />
      <el-table-column prop="number_returns" label="退货数量" width="100" align="right" />
      
      <!-- 退货原因和状态列 -->
      <el-table-column prop="purret_returncause" label="退货原因" width="200" />
      
      <!-- 时间列 -->
      <el-table-column prop="purret_returntime" label="退货时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.purret_returntime) }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.create_time) }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="pageCount"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElTable, ElTableColumn, ElTag, ElPagination } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  code: {
    type: String,
    required: true
  }
})

const rawData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const loading = ref(false)
const pageCount = ref(0)

// 处理后的表格数据
const processedTableData = computed(() => {
  const result = []
  rawData.value.forEach(pu => {
    if (pu.details && pu.details.length > 0) {
      pu.details.forEach((detail, index) => {
        result.push({
          ...pu,
          ...detail,
          // 添加一个标识用于合并单元格
          _rowSpan: index === 0 ? pu.details.length : 0
        })
      })
    } else {
      result.push({
        ...pu,
        _rowSpan: 1
      })
    }
  })
  return result
})

// 合并单元格方法
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 需要合并的列
  const mergeColumns = [
    'purret_code', 'po_code', 'po_name', 'vendor_name', 
    'vendor_code', 'purret_returncause', 'pu_state',
    'purret_returntime', 'create_time'
  ]
  
  if (mergeColumns.includes(column.property)) {
    if (row._rowSpan > 0) {
      return {
        rowspan: row._rowSpan,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString()
}



// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

const fetchData = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:5181/api/Pu/GetPuFyWhereSelect', {
      params: {
        Vendor_name: props.code,
        currentPage: currentPage.value,
        pageSize: pageSize.value
      },
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    rawData.value = response.data || []
  } catch (error) {
    ElMessage.error('获取退货记录失败: ' + error.message)
    console.error('API 错误:', error)
  } finally {
    loading.value = false
  }
}

// 获取总条数
const fetchTotalCount = async () => {
  try {
    const response = await axios.get('http://localhost:5181/api/Pu/GetPuWhereCount', {
      params: {
        Vendor_name: props.code
      },
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    pageCount.value = response.data || 0
  } catch (error) {
    console.error('获取总条数失败:', error)
  }
}

// 防御式数据监听
watch(() => props.code, (newVal, oldVal) => {
  if (newVal) {
    fetchTotalCount()
    fetchData()
  }
}, { immediate: true, deep: true })
</script>

<style scoped>
.vendorinfo_pu {
  padding: 20px;
}

.el-table {
  margin-top: 0px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>